<template>
    <div style="margin-top: 10px;margin-left: 20px">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item ><b>我的课堂</b></el-breadcrumb-item>
            <el-breadcrumb-item>课程表</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
    <div style="margin-top: 10px;">
        <el-row>
            <el-col :span="8">
                <el-button type="primary" @click="prevWeek">上一周</el-button>
                <el-button type="primary" @click="nextWeek">下一周</el-button>
            </el-col>
            <el-col :span="8" :offset="8" class="week-display">
                {{ weekRange }}
            </el-col>
        </el-row>

        <div class="schedule-table">
            <div class="day-header">
                <div class="day-column time-column"></div>
                <div class="day-column" v-for="day in daysOfWeek" :key="day">
                    <div>{{ day }}</div>
                </div>
            </div>
            <div class="schedule-content">
                <div class="day-column time-column">
                    <div class="time-slot" v-for="slot in timeSlots" :key="slot">{{ slot }}</div>
                </div>
                <div class="day-column" v-for="day in daysOfWeek" :key="day">
                    <div class="day-content">
                        <div
                            class="course-item"
                            v-for="course in getCoursesForDay(day)"
                            :key="course.startTime"
                            :style="getCourseStyle(course)"
                        >
                            <div class="course-title">{{ course.course }}</div>
                            <div class="course-details">{{ course.teacherName }}</div>
                            <div class="course-location">{{ course.location }}</div>
                            <div class="course-time">
                                {{ formatTime(course.startTime) }} - {{ formatTime(course.endTime) }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import dayjs from 'dayjs';
import utc from 'dayjs-plugin-utc';
import request8090 from "../../../../utils/request8090.js";
// 从 SessionStorage 获取 snumber
const snumber = sessionStorage.getItem('snumber');
if (!snumber) {
    ElMessage.error('未找到学号信息，请重新登录');
}

const currentWeek = ref(dayjs().startOf('week').format('YYYY-MM-DD'));
const courses = ref([]);  // 初始化为数组

// 获取课程表课程
const fetchCourses = async () => {
    try {
        const response = await request8090.get('http://localhost:8090/student/getschedule', {
            params: { sNumber: sessionStorage.getItem('snumber')  }
        });

        if (response.data.errorCode === 200) {
            courses.value = response.data.data;
        } else {
            ElMessage.error(response.data.msg || '获取数据失败');
        }
    } catch (error) {
        console.error('请求失败', error);
        ElMessage.error('请求失败');
    }
};
// 上一周按钮
const prevWeek = () => {
    currentWeek.value = dayjs(currentWeek.value).subtract(1, 'week').format('YYYY-MM-DD');
    fetchCourses();
};
// 下一周按钮
const nextWeek = () => {
    currentWeek.value = dayjs(currentWeek.value).add(1, 'week').format('YYYY-MM-DD');
    fetchCourses();
};

const formatTime = (time) => {
    return dayjs(time).format('HH:mm');
};

const weekRange = computed(() => {
    const startOfWeek = dayjs(currentWeek.value).startOf('week');
    const endOfWeek = dayjs(currentWeek.value).endOf('week');
    return `${startOfWeek.format('YYYY-MM-DD')} - ${endOfWeek.format('YYYY-MM-DD')}`;
});

const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

// 每小时一个时间段
const timeSlots = [
    '08:00 - 09:00', '09:00 - 10:00', '10:00 - 11:00', '11:00 - 12:00',
    '12:00 - 13:00', '13:00 - 14:00', '14:00 - 15:00', '15:00 - 16:00',
    '16:00 - 17:00', '17:00 - 18:00'
];

const getCoursesForDay = (day) => {
    const startOfWeek = dayjs(currentWeek.value).startOf('week');
    const dayIndex = daysOfWeek.indexOf(day);
    const targetDate = startOfWeek.add(dayIndex, 'day').format('YYYY-MM-DD');

    if (Array.isArray(courses.value)) {
        return courses.value.filter(course => {
            return dayjs(course.startTime).format('YYYY-MM-DD') === targetDate;
        });
    } else {
        return [];
    }
};

dayjs.extend(utc);

const getCourseStyle = (course) => {
    // 将时间转换为UTC时间
    const start = dayjs(course.startTime).utc();
    const end = dayjs(course.endTime).utc();

    // 每小时 85px，每分钟高度为 85 / 60
    const minuteHeight = 85 / 60;

    // 计算开始和结束的分钟数索引
    const startTimeSlotIndex = (start.hour() * 60) + start.minute();
    const endTimeSlotIndex = (end.hour() * 60) + end.minute();

    // 计算时间段的顶部位置和高度
    const top = (startTimeSlotIndex * minuteHeight) + 'px';
    const height = ((endTimeSlotIndex - startTimeSlotIndex) * minuteHeight) + 'px';

    return {
        top,
        height,
        position: 'absolute',
        width: '100%',
        boxSizing: 'border-box'
    };
};

onMounted(() => {
    fetchCourses();
});
</script>

<style scoped>
.schedule-table {
    display: flex;
    flex-direction: column;
    margin-top: 20px;
}

.day-header {
    display: flex;
    background-color: #f5f5f5;
    text-align: center;
    font-weight: bold;
    border-bottom: 1px solid #dcdcdc;
}

.day-column {
    width: 13%;
    position: relative;
}

.time-column {
    width: 10%;
    text-align: center;
    border-right: 1px solid #dcdcdc;
}

.time-slot {
    height:85px; /* 每小时85px */
    line-height: 30px;
    border-bottom: 1px solid #dcdcdc;
}

.schedule-content {
    display: flex;
}

.day-content {
    border: 1px solid #dcdcdc;
    border-top: none;
    height: 850px;
    position: relative;
}

.course-item {
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    margin: 0;
    padding: 5px;
    border-radius: 4px;
    box-sizing: border-box;
    overflow: hidden;
    position: absolute;
    width: 100%;
}

.course-title {
    font-weight: bold;
    margin-bottom: 5px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.course-details,
.course-location,
.course-time {
    font-size: 12px;
    color: #606266;
}
</style>
